package twitter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import utils.Pair;


import java.util.LinkedList;
import java.util.List;

public class Search {

    private final JSONObject searchResult;

    private Search(JSONObject result) {
        this.searchResult = result;
    }

    private static final String PART_SEARCH = "search";

    public static class Builder {

        private String query;

        public Builder setLocale(String locale) {
            this.locale = locale;
            return this;
        }

        private String locale;

        public Builder setType(String type) {
            this.type = type;
            return this;
        }

        private String type;

        public Builder setQuery(String query) {
            this.query = query;
            return this;
        }


        private int rpp;

        public Builder setRpp(int rpp) {
            this.rpp = rpp;
            return this;
        }

        private int page;

        public Builder setPage(int page){
            this.page = page;
            return this;
        }



        public Search build() {
            List<Pair<String, String>> params = new LinkedList<Pair<String, String>>();
            params.add(Pair.valueOf("q", query));
            if (locale != null) {
                params.add(Pair.valueOf("locale", locale));
            }
            if (rpp != 0) {
                params.add(Pair.valueOf("rpp", rpp + ""));
            }

            if (type != null){
                params.add(Pair.valueOf("result_type", type));
            }

            if (page != 0){
                params.add (Pair.valueOf("page", page + ""));

            }

            return new Search(NetUtil.downloadUrl(TwitterUri.createApiUri(PART_SEARCH, params)));

        }

    }

    public List<Tweet> getResult() {
        List<Tweet> result = new LinkedList<Tweet>();
        try {

            JSONArray jsonArray = searchResult.getJSONArray("results");

            for (int i = 0; i < jsonArray.length(); i++) {
                result.add(new Tweet(jsonArray.getJSONObject(i)));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return result;
    }

}
